<template>
  <div
      v-if="visible"
      ref="modalRef"
      :class="['common-modal', { 'draggable': draggable }]"
      :style="{
      zIndex: zIndex,
      left: position.x + 'px',
      top: position.y + 'px',
      width: width
    }"
      @mousedown="startDrag"
      role="dialog"
      aria-modal="true"
      :aria-labelledby="title"
  >
    <div class="modal-header">
      <span class="modal-title">{{ title }}</span>
      <button class="close-btn" @click="close" aria-label="关闭">
        <i class="icon-close"></i>
      </button>
    </div>
    <div class="modal-content">
      <slot></slot>
    </div>
    <div class="modal-footer">
      <button class="cancel-btn" @click="cancel">取消</button>
      <button class="confirm-btn" @click="confirm">确认</button>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useZIndex } from '@/composables/useZIndex'

const props = defineProps({
  title: { type: String, default: '模态框标题' },
  draggable: { type: Boolean, default: true },
  visible: { type: Boolean, default: false },
  width: { type: String, default: '400px' },
  initialPosition: {
    type: Object,
    default: () => ({ x: window.innerWidth / 2 - 200, y: window.innerHeight / 3 })
  }
})

const emit = defineEmits(['close', 'cancel', 'confirm'])

const { currentZIndex, incrementZIndex } = useZIndex()
const zIndex = computed(() => currentZIndex.value)

const modalRef = ref(null)
const isDragging = ref(false)
const position = ref({ ...props.initialPosition })
let startX = 0
let startY = 0

const startDrag = (e) => {
  if (props.draggable && (e.target === modalRef.value || e.target.closest('.modal-header'))) {
    isDragging.value = true
    startX = e.clientX
    startY = e.clientY
    document.addEventListener('mousemove', handleDrag)
    document.addEventListener('mouseup', stopDrag)
    incrementZIndex()
    e.preventDefault()
  }
}

const handleDrag = (e) => {
  if (isDragging.value) {
    const dx = e.clientX - startX
    const dy = e.clientY - startY
    startX = e.clientX
    startY = e.clientY

    position.value = {
      x: position.value.x + dx,
      y: position.value.y + dy
    }

    // 获取模态框的实际宽度（包括解析CSS中的px单位）
    const modalWidth = parseInt(props.width) || modalRef.value.offsetWidth
    const modalHeight = modalRef.value.offsetHeight

    // 修正边界检查，确保可以拖动到最右边
    position.value.x = Math.max(0, Math.min(position.value.x, window.innerWidth - modalWidth))
    position.value.y = Math.max(0, Math.min(position.value.y, window.innerHeight - modalHeight))
  }
}

const stopDrag = () => {
  isDragging.value = false
  document.removeEventListener('mousemove', handleDrag)
  document.removeEventListener('mouseup', stopDrag)
}

const handleKeydown = (e) => {
  if (e.key === 'Escape') {
    close()
  }
}

const close = () => {
  emit('close')
}

const cancel = () => {
  emit('cancel')
}

const confirm = () => {
  emit('confirm')
}

onMounted(() => {
  incrementZIndex()
  document.addEventListener('keydown', handleKeydown)
})

onUnmounted(() => {
  document.removeEventListener('mousemove', handleDrag)
  document.removeEventListener('mouseup', stopDrag)
  document.removeEventListener('keydown', handleKeydown)
})
</script>

<style scoped>
.common-modal {
  --primary-color: #00ff87;
  --secondary-color: #ff1f71;
  --accent-color: #60efff;
  --bg-dark: rgba(10, 20, 30, 0.95);
  --bg-light: rgba(255, 255, 255, 0.1);
  --text-primary: rgba(255, 255, 255, 0.9);
  --text-secondary: rgba(255, 255, 255, 0.7);
  --border-color: rgba(255, 255, 255, 0.2);
  --transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);

  position: fixed;
  background: var(--bg-dark);
  border-radius: 12px;
  border: 1px solid var(--border-color);
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
  color: var(--text-primary);
  font-family: 'Segoe UI', system-ui, -apple-system, sans-serif;
  overflow: hidden;
  transform: translate(0, 0); /* 移除之前的translate(-50%, 0) */
  transition: opacity 0.3s, transform 0.3s;
  user-select: none;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid var(--border-color);
  cursor: move;
  background: rgba(0, 0, 0, 0.2);
}

.modal-title {
  margin: 0;
  font-size: 1.2rem;
  font-weight: 600;
  background: linear-gradient(135deg, var(--secondary-color) 0%, #a020f0 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.close-btn {
  background: none;
  border: none;
  color: var(--text-secondary);
  cursor: pointer;
  padding: 4px;
  transition: var(--transition);
  border-radius: 4px;
}

.close-btn:hover {
  background: rgba(255, 255, 255, 0.1);
  color: var(--secondary-color);
}

.icon-close {
  display: inline-block;
  width: 20px;
  height: 20px;
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 24 24' stroke='currentColor'%3E%3Cpath stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M6 18L18 6M6 6l12 12' /%3E%3C/svg%3E");
  background-size: contain;
  background-repeat: no-repeat;
  background-position: center;
}

.modal-content {
  padding: 20px;
  max-height: 60vh;
  overflow-y: auto;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  padding: 16px 20px;
  border-top: 1px solid var(--border-color);
  background: rgba(0, 0, 0, 0.2);
  gap: 12px;
}

.cancel-btn, .confirm-btn {
  padding: 8px 20px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-family: inherit;
  font-weight: 500;
  transition: var(--transition);
}

.cancel-btn {
  background: var(--bg-light);
  color: var(--text-primary);
}

.cancel-btn:hover {
  background: rgba(255, 255, 255, 0.15);
  transform: translateY(-2px);
}

.confirm-btn {
  background: linear-gradient(135deg, var(--primary-color) 0%, var(--accent-color) 100%);
  color: #111;
}

.confirm-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 15px rgba(0, 255, 135, 0.3);
}

.modal-content::-webkit-scrollbar {
  width: 8px;
}

.modal-content::-webkit-scrollbar-track {
  background: rgba(255, 255, 255, 0.05);
  border-radius: 4px;
}

.modal-content::-webkit-scrollbar-thumb {
  background: rgba(255, 255, 255, 0.2);
  border-radius: 4px;
}

.modal-content::-webkit-scrollbar-thumb:hover {
  background: rgba(255, 255, 255, 0.3);
}

@media (max-width: 768px) {
  .common-modal {
    width: 90% !important;
    left: 50% !important;
    top: 20px !important;
    transform: translateX(-50%) !important;
  }

  .modal-footer {
    flex-direction: column;
  }

  .cancel-btn, .confirm-btn {
    width: 100%;
  }
}
</style>
